<script>
    import {mapState, mapGetters, mapMutations, mapActions} from 'vuex';
	import {isEmpty} from '@/utils/index';
	import {routeForNotification} from '@/utils/page'
	import {readFile,deleteFile,writeFile} from '@/utils/fileutil';
    import application from '@/settings/Application'
	import UserService from '@/services/user/index';
	import MsgService from '@/services/msg';
	const service = new UserService(false);
	const msgService = new MsgService(false,false);

    export default {
        data() {
            return {
				failedFileName:'failedStudyData.txt'
			}
        },
        methods: {
            ...mapActions({
                updateSystemInfo: 'settings/updateSystemInfo',
                updateNetWork:'settings/updateNetWork',
                restoreDataFromStorage:'user/restoreDataFromStorage',
            }),
            ...mapMutations({
                loadMessage:'user/loadMessage',
                updateVersionCode:'settings/updateVersionCode',
				setFileName:'msgStore/setFileName',
            }),
			initFileNames(){
				let _currentFileName = uni.getStorageSync('currentFileName');
				if(isEmpty(_currentFileName)){
					_currentFileName = `study${new Date().getTime()}.txt`;
				}
				console.log('===_currentFileName',_currentFileName);
				this.setFileName({
					lastFileName:'',
					currentFileName:_currentFileName
				});
			},
			saveFailedFile(data){
				writeFile(this.failedFileName,data);
			},
			//上传之前失败的文件
			reportFailedData(){
				return new Promise((resolve,reject)=>{
					try{
						readFile(this.failedFileName,(result,size)=>{
							if(isEmpty(result)){
								resolve('');
								return;
							}
							/**
							 * 经测试，每次最大应该在15k左右，如果失败数据大于50k,则认为失败次数过多（可能是服务器有问题），
							 * 避免本地数据太大舍弃保存的失败数据
							 */
							// console.log('=====数据大小字节：',size)
							if(size>50000){
								deleteFile(this.failedFileName);
							}
							// console.log('失败的数据：',result);
							let data = result.substring(0,result.length-1);
							const pageData = JSON.parse(`[${data}]`);
							const params = {data:pageData};
							msgService.reportPageData(params).then(response=>{
								if(response.success){
									//上传成功，删除本地文件
									deleteFile(this.failedFileName);
								}
								resolve('');
							}).catch((reason)=>{
								resolve('');
							});
						},()=>{
							resolve('');
						});
					}catch(e){
						resolve('');
					}
				});
			},
			reportPageData(){
				if(isEmpty(this.currentFileName)){
					return;
				}
				this.setFileName({
					lastFileName:this.currentFileName,
					currentFileName:`study${new Date().getTime()}.txt`
				});
				console.log('上传的文件：',this.lastFileName);
				readFile(this.lastFileName,(result)=>{
					if(!isEmpty(result)){
						let data = result.substring(0,result.length-1);
						const pageData = JSON.parse(`[${data}]`);
						const params = {data:pageData};
						// console.log('上传数据：',JSON.stringify(params));
						msgService.reportPageData(params).then(response=>{
							// console.log('回调数据：',JSON.stringify(response));
							if(response.success){
								//上传成功，删除本地文件
								deleteFile(this.lastFileName);
							}else{//接口失败
								this.saveFailedFile(result);
							}
						}).catch((reason)=>{
							this.saveFailedFile(result);
						});
					}
				});
			}
        },
        computed: {
            ...mapState({
                network: state => state.settings.network,
				currentFileName:(state)=>state.msgStore.currentFileName,
				lastFileName:(state)=>state.msgStore.lastFileName
            })
        },
        onLaunch: function () {
			//#ifdef APP-PLUS
			try{
				this.initFileNames();
				this.reportFailedData().then((res)=>{
					this.reportPageData();
				});
			}catch(e){
				console.log("====异常"+e);
			}
			//#endif
            this.restoreDataFromStorage();
            // #ifdef APP-PLUS
            plus.screen.lockOrientation("portrait-primary");
		
			/*
			验证token的有效
			1.如果有效，将vuex的user状态恢复，
			2.否则打开登录页面（可不做，已有逻辑处理了）
			 */
//             uni.getProvider({
//                 service: 'push',
//                 success: function (res) {
//                     console.log(res.provider)
// 
//                     // 个推的名称为 igexin
//                     if (~res.provider.indexOf('igexin')) {
//                         uni.subscribePush({
//                             provider: 'igexin',
//                             success: function (res) {
//                                 console.log('success:' + JSON.stringify(res));
//                             }
//                         });
//                     }
//                 }
//             });
           const $this = this;
           uni.getNetworkType({
               success: function (res) {
                   const {networkType,isConnected} = res;
                   $this.updateNetWork({networkType,isConnected});
               }
           });
           uni.onNetworkStatusChange(function (res) {
               const {isConnected,networkType} = res;
               $this.updateNetWork({isConnected,networkType})
               application.network.networkType = networkType;
               application.network.isConnected = isConnected;
           });
            // #endif
        },
        onShow: function () {
            uni.$emit('appShow');
			
        },
        onHide: function () {
			// #ifdef APP-PLUS
			if(uni.getSystemInfoSync().platform=='android'){
				plus.nativeUI.toast('智警学堂进入后台');
			}
			// #endif
			uni.$emit('appHide');
        },
        //捕获 app error
        onError(err) {
            uni.showToast({
                title: '系统发生了异常',
                duration: 2000,
                icon:'none'
            });
            console.error('捕获 app error:', err)
        }
    }
</script>
<style lang="scss" src="./App.scss"></style>
<style lang="scss">
//#ifndef APP-PLUS-NVUE	
    view,
    scroll-view,
    swiper,
    swiper-item,
    cover-view,
    cover-image,
    icon,
    text,
    rich-text,
    progress,
    button,
    checkbox,
    form,
    input,
    label,
    radio,
    slider,
    switch,
    textarea,
    navigator,
    audio,
    camera,
    image,
    video {
        box-sizing: border-box;
    }
	uni-button,
	button {
	    height: 80 upx;
	    line-height: 80 upx;
	    font-size: $font-lg + 2upx;
	    font-weight: normal;
	
	    &.no-border:before,
	    &.no-border:after {
	        border: 0;
	    }
	}
	
	uni-button[type=default],
	button[type=default] {
	    color: $font-color-dark;
	}
	.common-hover {
	    background: #f5f5f5;
	}
	
	

    /* 图片载入替代方案 */
    .image-wrapper {
        font-size: 0;
        background: #f3f3f3;
        border-radius: 4px;

        image {
            width: 100%;
            height: 100%;
            transition: .6s;
            opacity: 0;

            &.loaded {
                opacity: 1;
            }
        }
    }
	
	

    .clamp {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        display: block;
    }

    

    /*边框*/
    .b-b:after,
    .b-t:after {
        position: absolute;
        z-index: 3;
        left: 0;
        right: 0;
        height: 0;
        content: '';
        transform: scaleY(.5);
        border-bottom: 1px solid $border-color-base;
    }
	//#endif

    .b-b:after {
        bottom: 0;
    }

    .b-t:after {
        top: 0;
    }
    .input-placeholder {
        color: #999999;
    }

    .placeholder {
        color: #999999;
    }
</style>
